package cc.bookcloud.tool.ocr.common.sqlite;
/*==========================================================================
 * Copyright (C) Wit2Cloud Co.,Ltd
 * All Rights Reserved.
 * Created By 开源学社
 ==========================================================================*/

import cn.hutool.db.Db;
import cc.bookcloud.tool.ocr.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.sqlite.SQLiteConfig;
import org.sqlite.SQLiteDataSource;

import javax.annotation.Resource;
import java.sql.SQLException;

/**
 * @author John Goo
 * @version 1.0
 * @ClassName: Sqlite3Client
 * @Desc: TODO
 * @history v1.0
 */
@Slf4j
@Configuration
public class Sqlite3Client {

    @Resource
    private Environment environment;

    // 初始化数据源
    private SQLiteDataSource ds;

    public Sqlite3Client() {

    }

   // @PostConstruct
    public void init(){
        // 定义sqlite dbfile
        String dbPath = environment.getProperty("sqlite.db.path");
        if(StringUtil.isEmpty(dbPath)) {
            dbPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
            ///G:/2022-code/work-202205/release-assist-tool/target/classes/
            dbPath = dbPath.replace("/target/classes/","/src/main/resources");
        }
        dbPath = dbPath + "/x_release.db";
        String url = "jdbc:sqlite:"+dbPath;
        //防止读取jar报错
        url = "jdbc:sqlite:/SZJZ/assist-tool/x_release.db";
        try {
            Class.forName("org.sqlite.JDBC");
            SQLiteConfig conf = new SQLiteConfig();
            conf.setSharedCache(true);
            conf.setSynchronous(SQLiteConfig.SynchronousMode.OFF);
            conf.createConnection(url);
            ds = new SQLiteDataSource(conf);
            ds.setUrl(url);
        } catch (SQLException | ClassNotFoundException e) {
            log.error("[sqlite3] 初始化连接发生了异常！",e);
        }

    }

    public Db use(){
       return Db.use(ds);
    }

}
